
from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
from django_redis import get_redis_connection

from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

# from meiduo_mall.meiduo_mall.libs.captcha.captcha import captcha
from meiduo_mall.libs.captcha.captcha import captcha
from meiduo_mall.libs.yuntongxun.sms import CCP
from verifications import constants
from verifications import serializers
import random



class imagecodeAPIView(APIView):
    def get(self,request,image_code_id):
        # 拿到image_code_id
        # 生成图片和验证码内容
        text,image=captcha.generate_captcha()
        print(text)
        # 保存验证码redis
        redis_connect=get_redis_connection('verify_codes')
        redis_connect.setex('img_%s' % image_code_id,constants.IMAGE_CODE_REDIS_EXPIRES,text)
        return HttpResponse(image,content_type='images/jpg')



class SMSCodeView(GenericAPIView):
    serializer_class=serializers.CheckImageCodeSerializer

    def get(self,request,mobile):
        # 使用序列化器进行数据校验
        # 反序列化要传值
        serializer = self.get_serializer(data=request.query_params)
        serializer.is_valid(raise_exception=True)
        # 生成短信验证码
        sms_code = '%06d' % random.randint(0, 999999)
        print(sms_code)
        # 保存短信验证码及发送记录
        redis_connect = get_redis_connection('verify_codes')
        redis_connect.setex('sms_code_%s' % mobile,constants.SMS_CODE_REDIS_EXPIRES,sms_code)
        redis_connect.setex('send_flag_%s' % mobile,constants.SEND_SMS_CODE_INTERVAL,1)
        # 发送短信
        # ccp = CCP().send_template_sms(mobile, [sms_code, constants.SMS_CODE_REDIS_EXPIRES / 60], '1')
        return Response({'message':'ok'})



